<template>
  <div class="app-main-container">
    <div class="app-main-title">
      {{ copName }}
      <div class="goback" @click="goBack">
        <i class="el-icon-refresh-left" /> {{ translate("backPage") }}
      </div>
    </div>

    <el-form
      ref="form"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="auto"
      label-suffix="："
    >
      <div class="property-title">{{ translate("taskInfo") }}</div>
      <el-form-item :label="translate('taskName')" prop="name">
        <el-input
          v-model="param.name"
          class="w400"
          type="text"
          :placeholder="translate('taskNamePlace')"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item :label="translate('taskDesc')" prop="taskInfo">
        <el-input
          v-model="param.taskInfo"
          class="w400"
          type="text"
          :placeholder="translate('taskDescPlace')"
        />
      </el-form-item>
      <el-form-item :label="translate('roleConsumType')" prop="types">
        <el-select
          v-model="param.types"
          class="w400"
          multiple
          filterable
          :placeholder="translate('qxzzcss')"
        >
          <el-option
            v-for="item in orderTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="translate('yjblUnit')" prop="ratio">
        <el-input
          v-model="param.ratio"
          class="w400"
          oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
          type="text"
          :placeholder="translate('yjblUnitPlace')"
        />
      </el-form-item>
      <el-form-item :label="translate('dbqdje')" prop="beginMoney">
        <el-input
          v-model="param.beginMoney"
          class="w400"
          oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
          type="text"
          :placeholder="translate('qsrzxddje')"
        />
      </el-form-item>
      <el-form-item :label="translate('fybs')" prop="orderNum">
        <el-input
          v-model="param.orderNum"
          class="w400"
          oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
          type="text"
          :placeholder="translate('qsrzdddje')"
        />
      </el-form-item>
      <el-form-item :label="translate('indate')" prop="saleDate">
        <el-date-picker
          v-model="saleDate"
          class="w400"
          type="datetimerange"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="~"
          :start-placeholder="translate('kssj')"
          :end-placeholder="translate('jssj')"
        />
      </el-form-item>
      <el-form-item :label="translate('rwms')" prop="shareUsers">
        <el-radio v-model="param.shareUsers" label="0">{{
          translate("zdry")
        }}</el-radio>
        <el-radio v-model="param.shareUsers" label="1">{{
          translate("allUsers")
        }}</el-radio>
      </el-form-item>
      <el-form-item :label="translate('sortDx')">
        <el-input
          v-model="param.sortNum"
          class="w400"
          oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
          type="text"
          :placeholder="translate('sortDxPlace')"
        />
      </el-form-item>
      <div class="property-title">{{ translate("fxhbsz") }}</div>
      <el-form-item :label="translate('hbfxfm')" prop="sharePic">
        <template v-for="(item, index) in posterList">
          <el-radio
            :key="item.code"
            v-model="param.sharePic"
            :label="item.pic"
            @input="changePoster(index)"
            >{{ item.remaks }}</el-radio
          >
        </template>
        <el-radio
          v-model="param.sharePic"
          :label="sharePicLable"
          @input="changePoster(posterList.length)"
          >{{ translate("custom") }}</el-radio
        >
      </el-form-item>
      <el-form-item label="">
        <img
          v-show="selectPosterIndex != posterList.length"
          class="img"
          :src="param.pic2"
          alt=""
        />
        <div v-show="selectPosterIndex === posterList.length">
          <transition name="fade">
            <Cropper
              v-if="dialogCropperVisible2"
              :option-img="optionImg"
              :fileinfo="fileinfo"
              use-type="PUBLIC_IMG"
              :fixed-number="[32, 32]"
              @formSubmit="cropperSubmit2"
              @formClose="cropperClose2"
            />
          </transition>
          <el-upload
            class="device-uploader"
            :action="uploadFileUrl"
            :data="uploadParam"
            :auto-upload="false"
            :show-file-list="false"
            accept=".jpg,.png"
            :on-change="addFileChange2"
          >
            <img
              style="width: 84px; height: 84px"
              src="@/assets/images/btn_uploadcard.png"
              alt=""
            />
            <div
              v-show="param.pic2"
              class="file"
              :style="'background-image: url(' + param.pic2 + ')'"
            >
              <div class="delete">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage2"
                />
              </div>
            </div>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item :label="translate('qrcodeAddr')" prop="postion">
        <!-- <el-radio v-model="param.postion" label="0">{{translate('center')}}</el-radio> -->
        <el-radio v-model="param.postion" label="1">{{
          translate("lowLeft")
        }}</el-radio>
        <el-radio v-model="param.postion" label="2">{{
          translate("lowRight")
        }}</el-radio>
      </el-form-item>
      <el-form-item :label="translate('ewmtzdz')">
        <!-- <el-input
          v-model="param.shareUrl"
          class="w400"
          type="text"
          placeholder="例：/pages/pages/index"
        />
        <span class="placeholder6 ml20">查询小程序地址</span> -->
        <el-select
          v-model="param.shareUrl"
          class="w400"
          :placeholder="translate('qxzxcxdz')"
        >
          <el-option
            v-for="(item, index) in appUrls"
            :key="index"
            :label="item.name"
            :value="item.url"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="translate('hbfxbt')">
        <el-input
          v-model="param.shareTitle"
          class="w400"
          type="text"
          maxlength="50"
          :placeholder="translate('qsrfxbt')"
        />
      </el-form-item>
      <!-- <el-form-item label="分享/海报描述">
        <el-input
          v-model="param.shareInfo"
          class="w400"
          type="text"
          maxlength="50"
          placeholder="请输入分享描述，不超过50字"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button :loading="subLoading" type="primary" @click="onSubmit">{{
          translate("tj")
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { uploadFile, ShareConsumeTypes, CardStyles, addShare, ShareInfo, shareAppUrl } from '@/api'
import { rules } from '../config'
import Cropper from '@/components/cropper'
export default {
  name: 'TaskAdd',
  components: {
    Cropper
  },
  data() {
    return {
      id: '',
      copName: this.translate('taskAdd'),
      param: {
        shareFm: '',
        sharePic: '',
        shareUrl: '',
        types: []
      },
      saleDate: [],

      dialogCropperVisible: false,
      dialogCropperVisible2: false,
      optionImg: '',
      fileinfo: {},
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'PUBLIC_IMG'
      },

      subLoading: false,
      rules,
      orderTypeList: [],
      // coverList: [], // 封面
      // selectCoverIndex: 0,
      posterList: [], // 海报
      selectPosterIndex: 0,
      sharePicLable: '',
      appUrls: [],
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
          )
        }
      }
    }
  },
  created() {
    this.getShareConsumeTypes()
    this.getShareAppUrl()
    this.getImageList()

    setTimeout(() => {
      if (this.$route.query.id) {
        this.id = this.$route.query.id
        this.copName = this.translate('taskEdit')
        document.title = this.translate('taskEditShop')
        this.getShareDetail()
      }
    })
  },
  methods: {
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const { param, saleDate, id } = this
          if (saleDate.length > 0) {
            param.beginTime = saleDate[0]
            param.endTime = saleDate[1]
          }
          if (id) {
            param.id = id
          }
          this.subLoading = true
          addShare({ param }).then(res => {
            this.subLoading = false
            if (res.errorCode !== '000000') return
            this.$router.replace('/application/shareModule?activeTab=1&refresh=1')
            this.$message.success(this.translate('tjScs'))
          }, () => {
            this.subLoading = false
          })
        }
      })
    },
    getShareConsumeTypes() {
      ShareConsumeTypes({ param: {} }).then(res => {
        this.orderTypeList = res.recordList
      })
    },
    getImageList() {
      // CardStyles({ param: { type: 3 }}).then(res => {
      //   this.coverList = res.recordList
      //   if (res.recordList.length > 0) {
      //     this.param.shareFm = res.recordList[0].showPic
      //   }
      // })
      CardStyles({ param: { type: 4 } }).then(res => {
        this.posterList = res.recordList
        if (res.recordList.length > 0) {
          this.param.sharePic = res.recordList[0].showPic
        }
      })
    },
    getShareAppUrl() {
      shareAppUrl({ param: {} }).then(res => {
        this.appUrls = res.recordList
        if (res.recordList.length > 0) {
          this.param.shareUrl = res.recordList[0].url
        }
      })
    },
    getShareDetail() {
      const shareId = this.id
      ShareInfo({ param: { shareId } }).then(res => {
        this.param = { ...res.record }
        if (res.record.beginTime) {
          this.saleDate.push(res.record.beginTime)
        }
        if (res.record.endTime) {
          this.saleDate.push(res.record.endTime)
        }

        // 封面图片 回显
        // if (this.coverList.length > 0) {
        //   const coverListTemp = this.coverList.map(i => i.pic)
        //   const index = coverListTemp.indexOf(res.record.shareFm)
        //   if (index === -1) {
        //     this.selectCoverIndex = this.coverList.length
        //     this.param.pic = res.record.shareFmPath
        //     this.param.shareFm = res.record.shareFm
        //   } else {
        //     this.selectCoverIndex = index
        //   }
        // }
        if (this.posterList.length > 0) {
          const posterListTemp = this.posterList.map(i => i.pic)
          const index = posterListTemp.indexOf(res.record.sharePic)
          if (index === -1) {
            this.selectPosterIndex = this.posterList.length
            this.sharePicLable = res.record.sharePic
            this.param.pic2 = res.record.sharePicPath
            this.param.sharePic = res.record.sharePic
          } else {
            this.selectPosterIndex = index
            this.param.pic2 = this.posterList[index].showPic
            this.param.sharePic = this.posterList[index].pic
          }
        }
      })
    },
    changeCover(index) {
      if (index === this.coverList.length) {
        this.param.shareFm = ''
        this.param.pic = ''
      } else {
        this.param.shareFm = this.coverList[index].pic || ''
      }
    },
    changePoster(index) {
      this.selectPosterIndex = index
      if (index === this.posterList.length) {
        this.sharePicLable = ''
        this.param.sharePic = ''
        this.param.pic2 = ''
      } else {
        this.param.sharePic = this.posterList[index]['pic'] || ''
        this.param.pic2 = this.posterList[index]['showPic'] || ''
      }
    },
    // 上传成功
    uploadSuccess(response) {
      if (response.success) {
        this.$set(this.param, 'pic', response.showUrl)
        this.$set(this.param, 'shareFm', response.insertUrl)
      } else {
        this.$message.error(response.msg || this.translate('scsb'))
      }
    },
    uploadSuccess2(response) {
      if (response.success) {
        this.$set(this.param, 'pic2', response.showUrl)
        this.$set(this.param, 'sharePic', response.insertUrl)
      } else {
        this.$message.error(response.msg || this.translate('scsb'))
      }
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'pic', config.showUrl)
        this.$set(this.param, 'shareFm', config.insertUrl)
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || this.translate('scsb'))
        this.dialogCropperVisible = false
      }
    },
    cropperSubmit2(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'pic2', config.showUrl)
        this.$set(this.param, 'sharePic', config.insertUrl)
        this.$set(this, 'sharePicLable', config.insertUrl)
        this.dialogCropperVisible2 = false
      } else {
        this.$message.error(config.msg || this.translate('scsb'))
        this.dialogCropperVisible2 = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    cropperClose2() {
      this.dialogCropperVisible2 = false
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    async addFileChange2(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible2 = true
      })
    },
    // 删除场馆设施已上传图片
    deleteDeviceConfigAddImage() {
      this.$set(this.param, 'pic', '')
      this.$set(this.param, 'shareFm', '')
    },
    deleteDeviceConfigAddImage2() {
      this.$set(this.param, 'pic2', '')
      this.$set(this.param, 'sharePic', '')
    },
    goBack() {
      this.$router.replace('/application/shareModule?activeTab=1')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.img {
  width: 84px;
  height: 84px;
}
.device-uploader {
  width: 84px;
  height: 84px;
  display: flex;
  box-sizing: border-box;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>
